<template>
  <a-spin :spinning='confirmLoading'>
    <j-form-container :disabled='formDisabled'>
      <a-form :form='form' slot='detail'>
        <a-row>
          <a-col :span='12'>
            <a-form-item label='申请编号' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['code']" placeholder='申请编号自动生成' disabled />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='申请人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['createBy']" disabled />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='费用所属' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag type='list' v-decorator="['auditGrade', validatorRules.auditGrade]"
                                 :trigger-change='true' dictCode='audit_grade' placeholder='请选择费用所属'
                                 :disabled='model.bpmStatus=="3"'
              />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='出差类别' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag type='list' v-decorator="['travelType',validatorRules.travelType]"
                                 :trigger-change='true' dictCode='travel_type'
                                 placeholder='请选择出差类别'
                                 :disabled='model.bpmStatus=="3"'
                                 @change='typeChange' />
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if=" typeDictText =='2'|| model.projectId">
            <a-form-item label='项目名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                placeholder='请点击选择项目名称'
                v-decorator="['projectName',validatorRules.projectName]"
                :trigger-change='true'
                org-fields='id,short_name,customer_name'
                dest-fields='projectId,projectName,shortName'
                code='pm_project_select'
                :disabled='model.bpmStatus=="3"'
                @callback='projectNamePopupCallback'
              />
              <input v-decorator="['projectId']" v-show='false'></input>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if=" typeDictText =='1'|| model.customerId">
            <a-form-item label='客户简称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                placeholder='请点击选择客户'
                v-decorator="['shortName', validatorRules.shortName]"
                :trigger-change='true'
                org-fields='id,short_name'
                dest-fields='customerId,shortName'
                code='bus_customer_select'
                :disabled='model.bpmStatus=="3"'
                @callback='customerNamePopupCallback'
              />
              <a-input v-decorator="['customerId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12' v-if=" typeDictText =='1'|| model.opportunityId">
            <a-form-item label='商机名称' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-popup
                placeholder='请选择商机名称'
                v-decorator="['opportunityName']"
                :trigger-change='true'
                org-fields='id,name,num,short_name,sale_leader'
                dest-fields='opportunityId,opportunityName,opportunityNum,shortName,saleLeader'
                code='bus_business_opportunity_select'
                :disabled='model.bpmStatus=="3"'
                :param='{saleLeader: $store.getters.userInfo.realname}'
                @callback='popupCallback'
              />
              <a-input v-decorator="['opportunityId']" v-show='false'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='对接人' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['dockingPeople',validatorRules.dockingPeople]" placeholder='请输入对接人'
                       :disabled='model.bpmStatus=="3"'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='联系方式' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['contactWay',validatorRules.contactWay]" placeholder='请输入联系方式'
                       :disabled='model.bpmStatus=="3"'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='交通工具' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-dict-select-tag type='list' v-decorator="['vehicle',validatorRules.vehicle]" :trigger-change='true'
                                 dictCode='vehicle_type'
                                 :disabled='model.bpmStatus=="3"'
                                 placeholder='请选择交通工具' />
            </a-form-item>
          </a-col>
          <a-col :span='24'>
            <a-form-item label='出差目的' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <a-textarea v-decorator="['travelCause',validatorRules.travelCause]" rows='4' placeholder='请输入出差目的'
                          :disabled='model.bpmStatus=="3"' />
            </a-form-item>
          </a-col>

          <a-col :span='12'>
            <a-form-item label='开始时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-date placeholder='请选择开始时间' v-decorator="['startTime',validatorRules.startTime]"
                      :trigger-change='true'
                      style='width: 100%'
                      :disabled='model.bpmStatus=="3"'
                      @change='countNumOFDay2' />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='结束时间' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <j-date placeholder='请选择结束时间' v-decorator="['endTime',validatorRules.endTime]"
                      :trigger-change='true'
                      style='width: 100%'
                      :disabled='model.bpmStatus=="3"'
                      @change='countNumOFDay'
              />
            </a-form-item>
          </a-col>
          <a-col :span='12'>
            <a-form-item label='出差天数' :labelCol='labelCol' :wrapperCol='wrapperCol'>
              <a-input v-decorator="['numOfDay']" disabled placeholder='出差天数自动计算'></a-input>
            </a-form-item>
          </a-col>
          <a-col :span='24' v-if='model.bpmStatus=="3"'>
            <a-form-item label='总结' :labelCol='labelCol2' :wrapperCol='wrapperCol2'>
              <a-textarea v-decorator="['remake']" :autoSize='{minRows:4}' placeholder='请输入总结' />
            </a-form-item>
          </a-col>

          <a-col v-if='showFlowSubmitButton' :span='24' style='text-align: center'>
            <a-button @click='submitForm'>提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import moment from 'moment'

export default {
  name: 'HfOperateTravelApplyForm',
  components: {},
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  watch: {
    //流程表单的提交的监听事件，用来监听修改或者操作流程的表单
    // 同时需要修改 submitForm方法

    '$store.state.bpm.bpmSubmitStates': {
      immediate: true,
      handler(val) {
        if (val && val.edit && val.edit === '1') {
          this.submitForm().then(res => {
            if (res) {
              this.$store.commit('BPM_SUBMIT_STATES', {edit: '2'})
            }
          })
        }
      },
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      confirmLoading: false,
      validatorRules: {
        travelType: {
          rules: [
            { required: true, message: '请选择出差类别!' }
          ]
        },
        auditGrade: {
          rules: [
            { required: true, message: '请选择所属中心!' }
          ]
        },
        projectName: {
          rules: [
            { required: true, message: '请选择项目名称!' }
          ]
        },
        shortName: {
          rules: [
            { required: true, message: '请选择客户名称!' }
          ]
        },
        dockingPeople: {
          rules: [
            { required: true, message: '请输入对接人!' }
          ]
        },
        contactWay: {
          rules: [
            { required: true, message: '请输入联系方式!' }
          ]
        },
        vehicle: {
          rules: [
            { required: true, message: '请选择交通工具!' }
          ]
        },
        travelCause: {
          rules: [
            { required: true, message: '请填写出差目的!' }
          ]
        },
        startTime: {
          rules: [
            { required: true, message: '请选择开始时间!' }
          ]
        },
        endTime: {
          rules: [
            { required: true, message: '请选择结束时间!' }
          ]
        }

      },
      url: {
        add: '/operate/hfOperateTravelApply/add',
        edit: '/operate/hfOperateTravelApply/edit',
        queryById: '/operate/hfOperateTravelApply/queryById'
      },
      fields: [
        'code',
        'createBy',
        'auditGrade',
        'projectId',
        'projectName',
        'opportunityId',
        'opportunityName',
        'customerId',
        'shortName',
        'dockingPeople',
        'contactWay',
        'travelCause',
        'vehicle',
        'startTime',
        'endTime',
        'numOfDay',
        'remake',
        'travelType',
        'bpmStatus'
      ],
      typeDictText: ''
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData()
  },
  methods: {
    typeChange(value) {
      this.typeDictText = value
      this.model = {
        ...this.model,
        projectId: '',
        projectName: '',
        customerId: '',
        customerName: '',
        opportunityId: '',
        opportunityName: ''

      }
    },
    add() {
      this.edit({})
    },
    addRecord(record) {
      this.edit(record)
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, this.fields))
      })
    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId }
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result)
          }
        })
      }
    },
    submitForm() {
      const that = this
      return new Promise(((resolve, reject) => {
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true
            let httpurl = ''
            let method = ''
            if (!this.model.id) {
              httpurl += this.url.add
              method = 'post'
            } else {
              httpurl += this.url.edit
              method = 'put'
            }
            let formData = Object.assign(this.model, values)
            console.log('表单提交数据', formData)
            httpAction(httpurl, formData, method).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
                resolve(true)
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          } else {
            this.$store.commit('BPM_SUBMIT_STATES', {})
          }
        })
      }))
    },
    projectNamePopupCallback(row) {
      this.projectId = row.projectId
      this.form.setFieldsValue(pick(row, this.fields))
    },
    customerNamePopupCallback(row) {
      this.customerId = row.customerId
      this.form.setFieldsValue(pick(row, this.fields))
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, this.fields))
    },
    countNumOFDay(value) {
      let startTime = this.form.getFieldsValue(['startTime'])
      if (startTime.startTime == undefined || startTime.startTime == null) {
        this.form.setFieldsValue({ numOfDay: '0天' })
      } else {
        var num = moment(value).diff(moment(startTime.startTime), 'days')
        this.form.setFieldsValue({ numOfDay: (num + 1) + '天' })
      }
      console.log(startTime, value)
    },
    countNumOFDay2(value) {
      let endTime = this.form.getFieldsValue(['endTime'])
      if (endTime.endTime == undefined || endTime.endTime == null) {
        this.form.setFieldsValue({ numOfDay: '0天' })
      } else {
        var num = moment(endTime.endTime).diff(moment(value), 'days')
        this.form.setFieldsValue({ numOfDay: (num + 1) + '天' })
      }
      console.log(value, endTime)
    }
  }
}
</script>